﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using HDQApp.Common;
using HDQApp.Models;


namespace HDQApp
{
    public partial class AttrMgrForm : Form
    {
        public AttrMgrForm()
        {
            InitializeComponent();

            //为KeyDown能应用到所有控件上 注册 KeyDown 事件 
            foreach (Control control in this.Controls)
            {
                control.KeyDown += control_KeyDown;
            }
        }
        void control_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
            {
                this.Close();
            }
            else if (e.KeyCode== Keys.Delete)
            {
                btnDelete_Click(sender, e);
            }
        }
        private void AttrMgr_Load(object sender, EventArgs e)
        {
            SetMsg(true, "提示：当前状态 添加。");

            InitGrid();

            var lstSJLX = HDQApp.Models.数据类型.@int.GetListEnums();
            cboSJLX.Items.AddRange(lstSJLX.ToArray());

            var lstTXFL = HDQApp.Models.特性分类.订单物料特性.GetListEnums();
            cboTXFL.Items.AddRange(lstTXFL.ToArray());

        }

        void InitGrid()
        {
            string sel_sql = "(select a.Id,a.TeXMC AS 特性名称,a.MiaoS AS 描述,ShuJLX AS 数据类型,ShuJCD AS 数据长度,TeXFL AS 特性分类, b.TeZM AS 特征码,b.TeXZ AS 特性值,b.Id as bom_WuId  from sys_Register a LEFT JOIN bom_WuLTX b ON a.TeXMC=b.TeXMC) t";

            int total_Count = 0;
            DataTable data = DbHelperMsSQL.GetDataTableByPager(30, 1, "*", " t.Id asc", "", sel_sql, out total_Count);

            Grid.DataSource = data;


            Grid.Columns[0].Width = 40;
            Grid.Columns[1].Width = 80;
            Grid.Columns[1].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleLeft;
            Grid.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
            Grid.Columns[2].Width = 70;
            Grid.Columns[3].Width = 60;
            Grid.Columns[4].Width = 60;
            Grid.Columns[5].Width = 120;
            Grid.Columns[6].Width = 80;
            Grid.Columns[7].Width = 70;
            Grid.Columns[8].Visible = false;
        }


        private void btnAdd_Click(object sender, EventArgs e)
        {
            txtTeXMC.Text = string.Empty;
            txtMiaos.Text = string.Empty;
            cboSJLX.SelectedItem = null;
            txtSJCD.Text = string.Empty;
            cboTXFL.SelectedItem = null;

            txtTZM.Text = string.Empty;
            txtTXZ.Text = string.Empty;

            IsAdd = true;
            SetMsg(true, "提示：当前状态 添加。");
        }

        void SetMsg(bool isok, string msg)
        {
            labMsg.Text = msg;
            labMsg.ForeColor = isok ? Color.Green : Color.Red;
        }
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            InitGrid();
        }
        private void btnDelete_Click(object sender, EventArgs e)
        {
            DataGridViewSelectedRowCollection coll = Grid.SelectedRows;
            if (coll != null && coll.Count > 0)
            {
                DialogResult dResult = MessageBox.Show("确定要删除吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                if (dResult == System.Windows.Forms.DialogResult.OK)
                {
                    List<string> lstDel = new List<string>();
                    string del_sql = string.Empty;

                    del_sql = "delete from sys_Register where id=" + coll[0].Cells[0].Value.ToString();
                    lstDel.Add(del_sql);

                    del_sql = string.Format("delete from bom_WuLTX where TeXMC='{0}'", coll[0].Cells[1].Value);
                    lstDel.Add(del_sql);

                    int res = DbHelperMsSQL.ExecuteSqlTran(lstDel);

                    if (res > 0)
                    {
                        InitGrid();
                    }
                }
            }
        }

        bool IsAdd = true;
        private void btnSave_Click(object sender, EventArgs e)
        {

            if (string.IsNullOrWhiteSpace(txtTeXMC.Text))
            {
                SetMsg(false, "提示：特性名称不能为空！");
                txtTeXMC.Focus();
                return;
            }
            if (cboSJLX.SelectedItem == null)
            {
                SetMsg(false, "提示：数据类型不能为空！");
                cboSJLX.Focus();
                return;
            }
            if (cboSJLX.SelectedItem != null && !cboSJLX.SelectedItem.ToString().Equals("int", StringComparison.OrdinalIgnoreCase))
            {
                if (string.IsNullOrWhiteSpace(txtSJCD.Text))
                {
                    SetMsg(false, "提示：数据长度不能为空！");
                    txtSJCD.Focus();
                    return;
                }
                int len = 0;
                if (!int.TryParse(txtSJCD.Text, out len) || len < 1)
                {
                    SetMsg(false, "提示：数据长度必须为大于1的数字！");
                    txtSJCD.Focus();
                    return;
                }
            }

            if (cboTXFL.SelectedItem == null || string.IsNullOrWhiteSpace(cboTXFL.SelectedItem.ToString()))
            {
                SetMsg(false, "提示：特性分类不能为空！");
                cboTXFL.Focus();
                return;
            }
            if (string.IsNullOrWhiteSpace(txtTZM.Text))
            {
                SetMsg(false, "提示：特征码不能为空！");
                txtTZM.Focus();
                return;
            }



            sys_Register sysReg = new sys_Register();
            sysReg.TeXMC = txtTeXMC.Text.Trim();
            sysReg.Miaos = txtMiaos.Text.Trim();
            sysReg.ShuJLX = (数据类型)Enum.Parse(typeof(数据类型), cboSJLX.SelectedItem.ToString());
            sysReg.ShuJCD = Convert.ToInt32(txtSJCD.Text);
            sysReg.TeXFL = (特性分类)Enum.Parse(typeof(特性分类), cboTXFL.SelectedItem.ToString());

            bom_WuLTX bmWu = new bom_WuLTX();
            bmWu.TeXMC = sysReg.TeXMC;
            bmWu.TeZM = txtTZM.Text.Trim();
            bmWu.TeXZ = txtTXZ.Text.Trim();

            Hashtable ht = new Hashtable();
            List<SqlParameter> lstpara = new List<SqlParameter>();
            string insert_sql = string.Empty, update_sql = string.Empty;
            string msg = string.Empty;
            bool isok = false;


            if (IsAdd)
            {
                if (DbHelperMsSQL.Exists("select count(TeXMC) from sys_Register where TeXMC='" + sysReg.TeXMC + "'"))
                {
                    SetMsg(false, "该特性名称已经存在！(" + sysReg.TeXMC + ")");
                    return;
                }

                insert_sql = DbHelperMsSQL.GetInsertSql<sys_Register>(sysReg, new string[] { "id" }, out lstpara, null);
                ht.Add(insert_sql, lstpara.ToArray());

                insert_sql = DbHelperMsSQL.GetInsertSql<bom_WuLTX>(bmWu, new string[] { "id" }, out lstpara, null);
                ht.Add(insert_sql, lstpara.ToArray());

                isok = DbHelperMsSQL.ExecuteSqlTran(ht, out msg);

                msg = string.IsNullOrWhiteSpace(msg) ? "提示：添加成功。" : "提示：" + msg;
                SetMsg(isok, msg);
            }
            else
            {
                sysReg.Id = Convert.ToInt32(txtTeXMC.Tag.ToString());
                bmWu.Id = Convert.ToInt32(txtTZM.Tag);

                if (DbHelperMsSQL.Exists("select count(TeXMC) from sys_Register where TeXMC='" + sysReg.TeXMC + "' and Id!=" + sysReg.Id))
                {
                    SetMsg(false, "该特性名称已经存在！(" + sysReg.TeXMC + ")");
                    return;
                }

                update_sql = DbHelperMsSQL.GetUpdateSql<sys_Register>(sysReg, null, out lstpara, null);
                ht.Add(update_sql, lstpara.ToArray());


                update_sql = DbHelperMsSQL.GetUpdateSql<bom_WuLTX>(bmWu, null, out lstpara, null);
                ht.Add(update_sql, lstpara.ToArray());

                isok = DbHelperMsSQL.ExecuteSqlTran(ht, out msg);

                msg = string.IsNullOrWhiteSpace(msg) ? "提示：更新成功。" : "提示：" + msg;
                SetMsg(isok, msg);
            }
            InitGrid();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void Grid_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            if (e.StateChanged == DataGridViewElementStates.Selected)
            {
                txtTeXMC.Tag = e.Row.Cells["Id"].Value.ToString();

                txtTeXMC.Text = e.Row.Cells["特性名称"].Value.ToString();
                cboSJLX.SelectedItem = e.Row.Cells["数据类型"].Value.ToString();
                txtSJCD.Text = e.Row.Cells["数据长度"].Value.ToString();
                txtMiaos.Text = e.Row.Cells["描述"].Value.ToString();
                cboTXFL.SelectedItem = e.Row.Cells["特性分类"].Value.ToString();

                txtTZM.Tag = e.Row.Cells["bom_WuId"].Value.ToString();
                txtTZM.Text = e.Row.Cells["特征码"].Value.ToString();
                txtTXZ.Text = e.Row.Cells["特性值"].Value.ToString();

                IsAdd = false;
                SetMsg(true, "提示：当前状态 修改。");
            }
        }

        private void cboSJLX_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboSJLX.SelectedItem != null && cboSJLX.SelectedItem.ToString() == "int")
            {
                txtSJCD.Enabled = false;
            }
            else
            {
                txtSJCD.Enabled = true;
            }
        }

        private void txtTeXMC_Leave(object sender, EventArgs e)
        {
            if (txtTeXMC.Text.StartsWith("mt_", StringComparison.OrdinalIgnoreCase))
            {
                cboTXFL.SelectedItem = 特性分类.物料编码分解特性.ToString();
            }
            else if (txtTeXMC.Text.StartsWith("zp_", StringComparison.OrdinalIgnoreCase))
            {
                cboTXFL.SelectedItem = 特性分类.订单物料特性.ToString();
            }
            else if (txtTeXMC.Text.StartsWith("ss_", StringComparison.OrdinalIgnoreCase))
            {
                cboTXFL.SelectedItem = 特性分类.系统固定特性.ToString();
            }
            else
            {
                DialogResult dResult = MessageBox.Show("请确认特性名称的命名规范（物料编码的分解特性：mt_为前缀、订单物料的特性：zp_为前缀、系统固有特性：ss_为前缀）！", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                if (dResult == System.Windows.Forms.DialogResult.OK)
                {
                    txtTeXMC.Text = string.Empty;
                    txtTeXMC.Focus();
                }
            }
        }


    }
}
